package DepTree;

sub new {
	my($this)=[];
	my($classname)=shift;
	bless $this;
	return $this;
}


sub addroot {
	my($this) = shift;
	$this->[0]->{'root'} = shift;
}

sub createnode {
	my($this) = shift;
	my($word_num) = shift;

	$this->[$word_num]->{'noatt'} = 0;

}

sub addrel {
	my($this) = shift;
	my($word_num) = shift;
	my($relation) = shift;

	$this->[$word_num]->{'rel'} = $relation;
}

sub addrole {
	my($this) = shift;
	my($word_num) = shift;
	my($relation) = shift;
	$relation=~s/-//g;

	$this->[$word_num]->{'role'} = $relation;
}

sub addpos {
	my($this) = shift;
	my($word_num) = shift;
	my($partOfSpeech) = shift;

	$this->[$word_num]->{'pos'} = $partOfSpeech;
}

sub addFac {
	my($this) = shift;
	my($word_num) = shift;
	my($factorName) = shift;
	my($factorValue) = shift;

	$this->[$word_num]->{$factorName} = $factorValue;
}


sub addattch {
	my($this) = shift;
	my($word_num) = shift;
	my($child_num) = shift;
	
	$this->[$word_num]->{'noatt'}++;
	push(@{$this->[$word_num]->{'attch'}},$child_num);	

}

sub printDependencies {
	my($this) = shift;
	my($i,$j);
	for($i=0;$i<=$#$this;$i++) {
		print STDERR "$i,$this->[$i]->{'role'}(";
		foreach $j (@{$this->[$i]->{'attch'}}) {
			print STDERR $j.",";
		}
		print STDERR ") ";
	}
	print STDERR "\n";
}

sub printTree {
	my($this) = shift;
	my($node) = shift;
	my($i,$j);
	for($i=0;$i<=$#$this;$i++) {
		if(defined($node) && $node!=$i) {
			next;
		}
		print STDERR "$i";
		foreach $feat (sort {$b cmp $a} keys %{$this->[$i]}) {
			if($feat eq 'attch') {
				print STDERR "  (";
				foreach $j (@{$this->[$i]->{'attch'}}) {
					print STDERR $j.",";
				}
				print STDERR ")";
			}
			else {
				print STDERR "  $feat:$this->[$i]->{$feat}";
			}
		}
		print STDERR "\n";
	}
	print STDERR "---------------\n";
}

sub mergeTree {
	my($this) = shift;
	my($tomerge) = shift;
	my($offset) = $#$this+1;	
	my($i);
	for($i=0;$i<=$#$tomerge;$i++) {
		$this->createnode($offset+$i);
		foreach $feat (keys %{$tomerge->[$i]}) {
			if($feat eq 'attch') {
				foreach $j (@{$tomerge->[$i]->{'attch'}}) {
					$this->addattch($offset+$i,$j+$offset);
				}
			}
			elsif($feat ne 'root') {
				$this->addFac($offset+$i,$feat,$tomerge->[$i]->{$feat});
			}
		}
	}
	return $offset+$#$tomerge;
}

sub copyTree {
	my($this) = shift;
	my($tree) = shift;
	for($i=0;$i<=$#$tree;$i++) {
		$this->createnode($i);
		foreach $feat (keys %{$tree->[$i]}) {
			if($feat ne 'attch') {
				$this->addFac($i,$feat,$tree->[$i]->{$feat});
			}
			else {
				foreach $j (@{$tree->[$i]->{'attch'}}) {
					$this->addattch($i,$j);
				}
			}
		}
	}
}

1;
